<template>
    <el-card shadow="never">
        <template #header>
            <div class="card">
                <span class="cardContent">订单统计</span>
                <div>
                    <el-check-tag @click="handleChoose(item.value)" v-for="(item, index) in options" :key="index"
                        :checked="current == item.value" class="cardContentTag">{{ item.text
                        }}</el-check-tag>
                </div>
            </div>
        </template>
        <div ref="el" id="chart" style="width: 100%; height: 300px;"></div>
    </el-card>
</template>
<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import * as echarts from 'echarts';
import { statistics3 } from '@/api/index'
import { useResizeObserver } from '@vueuse/core'

const current = ref("week")
const options = [{
    text: "近一个月",
    value: 'month'
}, {
    text: "近一周",
    value: 'week'
}, {
    text: "近一天",
    value: 'hour'
}]

// 点击切换图表
const handleChoose = (value) => {
    current.value = value
    getData()
}

// 初始化图表
let myChart = ref(null)
onMounted(() => {
    let chartDom = document.getElementById('chart');
    if (chartDom) {
        myChart = echarts.init(chartDom);
        getData()
    }
})

onBeforeUnmount(() => {
    if (myChart) echarts.dispose(myChart)
})

function getData() {
    let option = {
        xAxis: {
            type: 'category',
            data: []
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                data: [],
                type: 'bar'
            }
        ]
    };

    myChart.showLoading()
    statistics3(current.value).then(res => {
        option.xAxis.data = res.x
        option.series[0].data = res.y
        option && myChart.setOption(option);
    }).finally(() => {
        myChart.hideLoading()
    })
}

const el = ref(null)
useResizeObserver(el, (entries) => myChart.resize())
</script>
<style scoped lang="less">
.card {
    display: flex;
    justify-content: space-between;

    .cardContent {
        font-size: 14px;
    }

    .cardContentTag {
        margin-right: 8px;
    }
}
</style>